
import inspect
import re
import textwrap

re_ws = re.compile(ur'([ ]+)')
re_ws_start = re.compile(ur'(^[ ]+)')
re_ws_rem = re.compile(ur'( +$)', re.M)
re_nl = re.compile(ur'(?<!\n)\n', re.M)
re_nls = re.compile(ur'\n{2,}', re.M)


def print_registry_doc(registry):
    wrapper = textwrap.TextWrapper(width=80, initial_indent='    ', subsequent_indent='    ')#, break_long_words=False, break_on_hyphens=False)
    for tool_name, tool in sorted(registry.items()):
        # print argspec
        string = [tool_name, '(']
        if inspect.isfunction(tool):
            argspec = inspect.getargspec(tool)
        elif inspect.isclass(tool):
            argspec = inspect.getargspec(tool.__init__)
            
        argsstring = []
            
        for arg in argspec.args:
            argsstring.append(arg)
            
            
        string.append(', '.join(argsstring))
        
        string.append(')')
        print '### Tool:',''.join(string),'\n'
        
        # Hack use inspect.getdoc() to do the de-indentation
        fixeddoc = inspect.getdoc(tool) or ''
        
        fixeddoc = re_ws_rem.sub('', fixeddoc)
        fixeddoc = re_nl.sub(' ', fixeddoc)
        
        for l in fixeddoc.split('\n'):
            for line in wrapper.wrap(l):
                print line
                
            print
        print
